<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Qweas Bookstore - Order Management</title>
    <link href="../css/ui.css" rel="stylesheet"/>
    <link href="../css/framework.css" rel="stylesheet"/>
    <link href="../css/admin.css" rel="stylesheet"/>
    <link href="../css/font-awesome.min.css" rel="stylesheet"/>

    <!-- Import jQuery, Bootstrap and DataTables -->
    <link rel="stylesheet" type="text/css" href="../css/bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" href="../assets/DataTables-1.10.16/css/dataTables.bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" href="../assets/FixedHeader-3.1.3/css/fixedHeader.bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" href="../assets/KeyTable-2.3.2/css/keyTable.bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" href="../assets/Responsive-2.2.1/css/responsive.bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" href="../assets/Scroller-1.4.4/css/scroller.bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" href="../assets/Select-1.2.5/css/select.bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" href="../css/bootstrap-select.min.css"/>

    <script type="text/javascript" src="../js/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="../js/bootstrap.min.js"></script>
    <script type="text/javascript" src="../assets/DataTables-1.10.16/js/jquery.dataTables.min.js"></script>
    <script type="text/javascript" src="../assets/DataTables-1.10.16/js/dataTables.bootstrap.min.js"></script>
    <script type="text/javascript" src="../assets/FixedHeader-3.1.3/js/dataTables.fixedHeader.min.js"></script>
    <script type="text/javascript" src="../assets/KeyTable-2.3.2/js/dataTables.keyTable.min.js"></script>
    <script type="text/javascript" src="../assets/Responsive-2.2.1/js/dataTables.responsive.min.js"></script>
    <script type="text/javascript" src="../assets/Responsive-2.2.1/js/responsive.bootstrap.min.js"></script>
    <script type="text/javascript" src="../assets/Scroller-1.4.4/js/dataTables.scroller.min.js"></script>
    <script type="text/javascript" src="../assets/Select-1.2.5/js/dataTables.select.min.js"></script>
    <script type="text/javascript" src="../js/bootstrap-select.min.js"></script>

    <script>
        var currentSelectedRowData = null, table = null, tableOrderDetails = null;
        var currentSelectedItemRow = null;
        const ORDERID = 'OrderId', ADDRESS = 'Address', TPRICE = 'totalPrice', DATE = 'CreateDate', STATUS = 'STATUS',
            VC = 'VC', USERNAME = 'UserName';
    </script>
</head>
<body>
<div id="header">
    <img id="imgLogo" style="margin-left: 10px" src="../images/bookstore_logo.png"/>
    <div id="navbar" align="right">
        <!-- Control buttons -->
        <div id="toggleBookMgr" class="ctrl-panel-item font-navbar ctrl-left">
            <a href="admin.jsp"><i class="fa fa-book font-navbar"></i>&nbsp;Books</a>
        </div>
        <div id="toggleUserMgr" class="ctrl-panel-item font-navbar">
            <a href="usermgr.jsp"><i class="fa fa-users font-navbar"></i>&nbsp;Customers</a>
        </div>
        <div id="toogleCommentMgr" class="ctrl-panel-item font-navbar">
            <a href="commentmgr.jsp"><i class="fa fa-comment font-navbar"></i>&nbsp;Comments</a>
        </div>
        <div id="toggleOrderMgr" class="ctrl-panel-item font-navbar  ctrl-active ctrl-right">
            <a href="#"><i class="fa fa-dollar font-navbar"></i>&nbsp;Orders</a>
        </div>&nbsp;&nbsp;&nbsp;
        <!-- Logout -->
        <div id="btnSignout" class="navbar_item div-button font-navbar">
            <i class="fa fa-sign-out font-navbar"></i>&nbsp;EXIT
        </div>
    </div>
</div>
<div id="content">
    <!-- CONTENTS -->
    <div class="bs-container">
        <div class="bs-container-left">
            <!-- Operation Panel -->
            <div class="group-panel operation-panel">
                <div class="group-panel-header"><i class="fa fa-gear font-panel-header"></i>&nbsp;OPERATIONS</div>
                <div id="btnEditOrderDetails" class="operation-panel-item" style="margin-top: 5px">
                    <i class="fa fa-edit green small-icon"></i>&nbsp;Edit Order Details...
                </div>
                <div id="btnUpdateOrder" class="operation-panel-item">
                    <i class="fa fa-upload blue small-icon"></i>&nbsp;Update Order Status
                </div>
            </div>
        </div>
        <div class="bs-container-right">
            <div class="group-panel booklist-panel">
                <div class="group-panel-header"><i class="fa fa-search font-panel-header"></i>&nbsp;ORDER MANAGEMENT</div>
                <!-- Alert Area -->
                <div class="group-panel-alerts">
                    <!-- success -->
                    <div class="alert alert-success group-panel-alert hidden" id="alert-success">
                        <button type="button" class="close"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
                        <span></span>
                    </div>
                    <!-- error -->
                    <div class="alert alert-danger group-panel-alert hidden" id="alert-error">
                        <button type="button" class="close"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
                        <span></span>
                    </div>
                </div>
                <div id="table-container">
                    <table id="orderTable" class="table table-striped table-bordered table-hover no-cursor" style="width: 100%;">
                        <thead>
                        <tr>
                            <th>Order ID</th>
                            <th>Customer</th>
                            <th>Total Price</th>
                            <th>Date</th>
                            <th>V.C</th>
                            <th>Status</th>
                            <th>Address</th>
                        </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <!--  END OF CONTENT -->
</div>

<!-- Modal Forms -->
<div id="modalUpdateOrderStatus" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;
                </button>
                <h4 class="modal-title">Update Order Status %TEXT%</h4>
            </div>
            <form class="form-horizontal" action="../UpdateOrderStatusServlet" method="post" id="updatestatus_form" role="form"
                  data-toggle="validator">
                <div class="modal-body">
                    <div class="control-group">
                        <label class="col-md-4 control-label">Current Status</label>
                        <div class="controls">
                            <select id="ddlOldStatus" class="col-md-6 selectpicker" disabled>
                                <option value="-1">Payment Pending</option>
                                <option value="0">Delivery Pending</option>
                                <option value="1">Delivery in Progress</option>
                                <option value="2">Delivered</option>
                                <option value="3">Commented</option>
                            </select>
                            <p class="help-block"></p>
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="col-md-4 control-label">New Status</label>
                        <div class="controls">
                            <select id="ddlNewStatus" class="col-md-6 selectpicker" required>
                                <option value="-1" disabled>Payment Pending</option>
                                <option value="0" disabled>Delivery Pending</option>
                                <option value="1" >Delivery in Progress</option>
                                <option value="2" disabled>Delivered</option>
                            </select>
                            <p class="help-block"></p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" data-dismiss="modal" id="btnUpdateOrderStatus">Update</button>
                </div>
            </form>
            <script>
                //$('#updatestatus_form').submit(function (){
                $('#btnUpdateOrderStatus').click(function () {
                    $.ajax({
                        data: {
                            orderId: currentSelectedRowData[ORDERID],
                            status: $('#ddlNewStatus').val()
                        },
                        type:"post",
                        url:"../UpdateOrderStatusServlet",
                        success: function(response) {
                            if(response === "UpdateOrderStatusSuccess") {
                                RefreshOrderTable();
                                PushAlert("success", "Success", "Order status updated.");
                            } else
                                PushAlert("error", "Error", "Failed to update order status. Please try again later.");
                        },
                        error: function(response) {
                            $('#modalUpdateOrderStatus').modal('hide');
                            PushAlert("error", "Error", "An error occurred while communicating with the server.");
                        }
                    });
                });
            </script>
        </div>
    </div>
</div>

<div id="modalEditDetails" class="modal fade" tabindex="-2" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;
                </button>
                <h4 class="modal-title">Edit order details</h4>
            </div>
            <div class="modal-body">
                <table id="detailTable" class="table table-striped table-bordered table-hover no-cursor"
                       style="width: 100%; margin: 5px auto;">
                    <thead>
                    <tr>
                        <th>Book ID</th>
                        <th>Title</th>
                        <th>Author</th>
                        <th>Price</th>
                        <th>Quantity</th>
                    </tr>
                    </thead>
                    <tbody></tbody>
                </table>
                <hr/>
                <div class="control-group">
                    <div class="input-group">
                        <input name="new_quantity" id="new_quantity" placeholder="New quantity"
                               min="1" step="1" data-number-to-fixed="2" data-number-stepfactor="100"
                               class="form-control" type="number" required/>
                        <div class="input-group-btn">
                            <button id="btnDeleteItem" type="button" class="btn btn-danger"
                                    onclick="AjaxAlterQuantity('delete')" >Delete</button>
                            <button id="btnAlterQuantity" type="button" class="btn btn-default"
                                    onclick="AjaxAlterQuantity('alter')" >Update</button>
                        </div>
                    </div>
                </div>
                <script>
                    function AjaxAlterQuantity(action) {
                        if(currentSelectedItemRow == null)
                            return;
                        let orderId = currentSelectedRowData[ORDERID];
                        let bookId = currentSelectedItemRow['BookId'];
                        let quantity = action === "delete" ? 0 : $('#new_quantity').val();

                        $.ajax({
                            data: {
                                OrderId: orderId,
                                BookId: bookId,
                                NewQuantity: quantity
                            },
                            type: 'POST',
                            url: '../AlterSingleOrderItemServlet',
                            success: function(response) {
                                console.log(response);
                                if(response === "success") {
                                    LoadOrderItems();
                                    if(action === "delete")
                                        SetDetailModalComponemnt(null);
                                } else
                                    alert('Failed to alter the item. Please try again later.');
                            },
                            error: function (xhr, desc, err) {
                                alert('Service not available at this moment.');
                            }
                        });
                    }
                </script>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-dismiss="modal">Finish
                </button>
            </div>
        </div>
    </div>
</div>

<div id="footer" align="center">
    <p style="font-size: 13px; color: lightgray;">
        © 2018 Qweas Bookstore, Zhang Wenqiang, Wu Jiatian, Ethan Phung, Andrew Lu and Eric Shuai. All rights
        reserved.</p>
</div>

<script>
    // Hide all alerts
    $('.group-panel-alert').hide().removeClass('hidden'); // to prevent weird flash
    SetDetailModalComponemnt(null);

    $(document).ready(function() {
        table = $('#orderTable').DataTable({
            paging: true, autoWidth: true, ordering: true,
            columns: [
                { data: 'OrderId' },
                { data: 'UserName' },
                { data: 'totalPrice' },
                { data: 'CreateDate' },
                { data: 'VC' },
                { data: 'STATUS' },
                { data: 'Address' }
            ],
            createdRow: function(row, data, index) {
                var statusStr = "Unknown";

                // replace STATUS with human-friendly text
                switch(parseInt(data[STATUS])) {
                    case -1: statusStr = "Payment pending"; break;
                    case 0: statusStr = "Delivery pending"; break;
                    case 1: statusStr = "Delivery in progress"; break;
                    case 2: statusStr = "Delivered"; break;
                    case 3: statusStr = "Commented"; break;
                }
                console.log(statusStr);
                $('td', row).eq(5).html(statusStr); // STATUS

            },
            ajax: {
                url: "../GetAllOrderServlet",
                type: "POST",
                dataSrc: ''
            }
        });

        // Bind table click event
        $('#orderTable tbody').on('click', 'tr', function () {
            currentSelectedRowData = table.row(this).data();

            if ($(this).hasClass('selected')) {
                $(this).removeClass('selected');
                currentSelectedRowData = null;
            } else {
                table.$('tr.selected').removeClass('selected');
                $(this).addClass('selected');
            }
        });

        $('#detailTable tbody').on('click', 'tr', function () {
            if ($(this).hasClass('selected')) {
                $(this).removeClass('selected');
                SetDetailModalComponemnt(null);
            } else {
                tableOrderDetails.$('tr.selected').removeClass('selected');
                $(this).addClass('selected');
                SetDetailModalComponemnt(tableOrderDetails.row(this).data());
            }
        });

        $('#btnUpdateOrder').click(function() {
            if(currentSelectedRowData != null && currentSelectedRowData[STATUS] == 0) {
                $('#ddlOldStatus').selectpicker('val', currentSelectedRowData[STATUS]);
                $('#modalUpdateOrderStatus .modal-title').text("Update Order Status - "+currentSelectedRowData[ORDERID]);
                $('#modalUpdateOrderStatus').modal('show');
            } else
          		PushAlert("info", "Error", "No action available for this transaction.");
        });

        $('#btnEditOrderDetails').click(function (){
            if(currentSelectedRowData != null) {
                LoadOrderItems();
                $('#modalEditDetails').modal('show');
            }
        });
        
        $('#btnSignout').click(function () {
        	window.location.replace("../login.jsp");
        });
    });

    function PushAlert(type, title, message) {
        let object = (type === "success") ? $('#alert-success') : $('#alert-error');
        let span = object.children('span');
        let timer, timeout = 3000; // 3s

        span.html("<strong>" + title + "!</strong>&nbsp;" + message);
        object.appendTo('.group-panel-alerts');
        object.slideDown();

        // Set timeout
        clearTimeout(timer);
        timer = window.setTimeout(function(){
            object.slideUp();
            span.innerHTML = ""; // clear
        }, timeout);
    }

    function RefreshOrderTable() {
        table.ajax.reload();
    }

    function LoadOrderItems() {
        if(tableOrderDetails == null) {
            tableOrderDetails = $('#detailTable').DataTable({
                columns: [
                    { data: 'BookId' },
                    { data: 'BookName' },
                    { data: 'Author' },
                    { data: 'Price' },
                    { data: 'Quantity' }
                ],
                ajax: {
                    url: '../FetchOrderDetailsServlet',
                    type: 'POST',
                    data: function(d) {
                        if(currentSelectedRowData != null)
                            d.OrderId = currentSelectedRowData[ORDERID];
                    },
                    dataSrc: ''
                }
            });
        } else
            tableOrderDetails.ajax.reload();
    }

    function SetDetailModalComponemnt(row) {
        if(row === null) {
            $('#new_quantity').val('').prop('disabled', true);
            $('#btnDeleteItem').prop('disabled', true);
            $('#btnAlterQuantity').prop('disabled', true);
        } else {
            $('#new_quantity').val(row['Quantity']).prop('disabled', false);
            $('#btnDeleteItem').prop('disabled', false);
            $('#btnAlterQuantity').prop('disabled', false);
        }
        currentSelectedItemRow = row;
    }
</script>
</body>
</html>